{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e50afff0",
   "metadata": {},
   "source": [
    "# Prior Knowledge"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b23b6fb",
   "metadata": {},
   "source": [
    "When performing causal discovery, a user may have some domain knowledge which may allow them to specify one or multiple of the following:\n",
    "1. A directional link between certain pairs of nodes are forbidden.\n",
    "2. A directional link exists between certain pairs of nodes.\n",
    "3. Nodes that are root variables, i.e., they have no parents (incoming causal links).\n",
    "4. Nodes that are leaf variables, i.e., they have no children (no outgoing links).\n",
    "5. Two nodes are co-parents (used for Markov Blanket discovery only).\n",
    "\n",
    "To allow such user specifications, we support the **PriorKnowledge** class which can be initialized with the relevant prior knowledge about the graph. If a PriorKnowledge instance is created, it can be passed to the causal discovery algorithm being used, where it will enforce these conditions. Note that specifying the PriorKnowledge object is optional and not needed if the user has no prior knowledge about the variables.\n",
    "\n",
    "The reason for supporting this functionality is that it helps improve the accuracy of the discovered causal graph, which may otherwise contain spurious or missing links due to many possible reasons such as insufficient data or data violating the causal model assumption.\n",
    "\n",
    "We begin by importing the PriorKnowledge class object.\n",
    "\n",
    "**Note:** For example usage of prior knowledge in causal discovery algorithms, see the Tabular PC tutorial and the Grow-Shrink tutorial."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4ba6ba0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from causalai.models.common.prior_knowledge import PriorKnowledge"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "deba5797",
   "metadata": {},
   "source": [
    "## Tabular Data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32158ff7",
   "metadata": {},
   "source": [
    "We now show an example of how to specify prior knowledge. For this example, consider a tabular data which has 4 variables named A,B,C, and D. Suppose we want to specify that the links C->A, C->B, and D->C are forbidden (read as: C causes A, C causes B, and D causes C are forbidden). This can be done as follows."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ca226383",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "forbidden_links = {'A': ['C'], 'B': ['C'], 'C': ['D']}\n",
    "prior_knowledge = PriorKnowledge(forbidden_links=forbidden_links)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebf47bc7",
   "metadata": {},
   "source": [
    "Suppose that we additionally wanted to specify that the link A->B exists. This can be done as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "7a2f77e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "forbidden_links = {'A': ['C'], 'B': ['C'], 'C': ['D']}\n",
    "existing_links = {'B': ['A']}\n",
    "prior_knowledge = PriorKnowledge(forbidden_links=forbidden_links, existing_links=existing_links)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dfbcd6d0",
   "metadata": {},
   "source": [
    "Notice that:\n",
    "1. forbidden_links and existing_links are specified as dictionaries.\n",
    "2. if an argument (E.g. existing_links) is not specified, it is assumed to be empty. This holds true for all the four arguments of PriorKnowledge: root_variables, leaf_variables, forbidden_links, existing_links.\n",
    "\n",
    "Below we show how to specify root_variables and leaf_variables. Note that they are specified as lists.\n",
    "\n",
    "For this example, suppose we want to specify that D is a leaf variable and A is a root variable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f09a58d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "root_variables = ['A']\n",
    "leaf_variables = ['D']\n",
    "prior_knowledge = PriorKnowledge(root_variables=root_variables, leaf_variables=leaf_variables)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b6f3bbf",
   "metadata": {},
   "source": [
    "PriorKnowledge also allow specification of existing and forbidden co-parents, which is used only for Markov Blanket discovery. Furthermore, PriorKnowledge attempts to deduce additional information about co-parents from other provided information (unless the user explicitly sets fix_co_parents as False) as follows:\n",
    "\n",
    "1. If existing_links implies some co-parent relationships, those will be added to existing_co_parents\n",
    "2. If leaf_variables forbids some co-parent relationships, those will be added as forbidden_co_parents for any variable for which this fix is requested by passing it to var_names.\n",
    "\n",
    "Because co-parenting is a symmetric relationship, information implied by this symmetry is also added. This happens regardless of the value of fix_co_parents.\n",
    "\n",
    "Note that the expansion is not guaranteed to include all implications."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "90754143",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "existing_co_parents: {'B': ['E'], 'A': ['E'], 'E': ['B', 'A']}\n",
      "forbidden_co_parents: {'B': ['C'], 'E': ['D'], 'F': ['D'], 'C': ['B'], 'D': ['E', 'F']}\n"
     ]
    }
   ],
   "source": [
    "forbidden_links = {'A': ['C'], 'B': ['C'], 'C': ['D']}\n",
    "existing_links = {'B': ['A','E']}\n",
    "root_variables = ['A']\n",
    "leaf_variables = ['D']\n",
    "existing_co_parents = {'B': ['E']}\n",
    "forbidden_co_parents = {'B': ['C']}\n",
    "var_names = ['E','F'] \n",
    "# var_names: This is used only to expand forbidden_co_parents using the leaf_variables information in prior knowledge.\n",
    "# var_names: we recommend adding any variable for which you’d like to compute a markov blanket.\n",
    "\n",
    "prior_knowledge = PriorKnowledge(root_variables=root_variables, leaf_variables=leaf_variables,\n",
    "                                 existing_links=existing_links, forbidden_links=forbidden_links,\n",
    "                                 existing_co_parents=existing_co_parents, forbidden_co_parents=forbidden_co_parents,\n",
    "                                 var_names=var_names)\n",
    "\n",
    "print(f\"existing_co_parents: {prior_knowledge.existing_co_parents}\")\n",
    "print(f\"forbidden_co_parents: {prior_knowledge.forbidden_co_parents}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ef0964e7",
   "metadata": {},
   "source": [
    "Since the links A -> B and E -> B exist, PriorKnowledge deduces that A and E are co-parents. Since D is a leaf variable, it cannot be a co-parent, and so it can be added as a forbidden co-parent for any variable we want (which we specified in var_names)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce0fbc15",
   "metadata": {},
   "source": [
    "## Time Series Data\n",
    "\n",
    "For time series data, PriorKnowledge can be specified in the same format as shown above for tabular data. This means that the PriorKnowledge for time series is time index agnostic."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "debad0c3",
   "metadata": {},
   "source": [
    "## PriorKnowledge: Useful methods\n",
    "\n",
    "Finally, we describe the class method **isValid(parent, child)** of PriorKnowledge, which is used internally by our causal discovery algorithms, but optionally may be of use to users.\n",
    "\n",
    "This method essentially takes the name or index of 2 nodes as input, and outputs whether this causal link is allowed by the PriorKnowledge instance or not. If PriorKnowledge does not specify anything about this causal link, or PriorKnowledge is not instantiated using any arguments at all, the output will be always True.\n",
    "\n",
    "Let's use all the conditions specified in the above examples in the example below:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "292314d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "forbidden_links = {'A': ['C'], 'B': ['C'], 'C': ['D']} # C cannot be a parent of A and B, and D cannot be a parent of C\n",
    "existing_links = {'B': ['A']} # A is a parent of B\n",
    "root_variables = ['A']\n",
    "leaf_variables = ['D']\n",
    "prior_knowledge = PriorKnowledge(forbidden_links=forbidden_links, \n",
    "                                 existing_links=existing_links,\n",
    "                                 root_variables=root_variables,\n",
    "                                 leaf_variables=leaf_variables)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "91cfdab3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Is the link C->A allowed? False\n",
      "Is the link C->B allowed? False\n",
      "Is the link D->C allowed? False\n",
      "\n",
      "Is the link A->B allowed? True\n",
      "\n",
      "Is the link B->A allowed? False\n",
      "Is the link D->B allowed? False\n",
      "\n",
      "Is the link B->C allowed? True\n"
     ]
    }
   ],
   "source": [
    "print(f\"Is the link C->A allowed? {prior_knowledge.isValid('C', 'A')}\") # specified as forbidden above\n",
    "print(f\"Is the link C->B allowed? {prior_knowledge.isValid('C', 'B')}\") # specified as forbidden above\n",
    "print(f\"Is the link D->C allowed? {prior_knowledge.isValid('D', 'C')}\") # specified as forbidden above\n",
    "\n",
    "print(f\"\\nIs the link A->B allowed? {prior_knowledge.isValid('A', 'B')}\") # specified as existing above\n",
    "\n",
    "print(f\"\\nIs the link B->A allowed? {prior_knowledge.isValid('B', 'A')}\")# A specified as root, thus cannot be a child\n",
    "print(f\"Is the link D->B allowed? {prior_knowledge.isValid('D', 'B')}\")# D specified as leaf, thus cannot be a parent\n",
    "\n",
    "\n",
    "# nothing specified, hence allowed. Note index of B=1, and index of C=2. Just to show that we can use variable indices\n",
    "print(f\"\\nIs the link B->C allowed? {prior_knowledge.isValid(1, 2)}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
